<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/2/24
 * Time: 13:27
 */

namespace Modules\Admin\Service;

use HiCommon\Model\GiftExtend;
use HiCommon\Repository\CouponsRepository;
use HiCommon\Repository\GiftRepository;
use HiCommon\Repository\GiftExtendRepository;
use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\LogRepository;

use HiCommon\Repository\UserInviteRepository;
use HiCommon\Repository\UsersRepository;
class GiftService
{


    /**
     *  获取指定类型的 优惠券
     *  hinq 2020 2 25
     *  凌晨三点
     *  $type           1：新用户注册  2：老用户回馈  3：邀请有礼
     *  $type_shop      1：普通商品   2：服务商品   3：保养套餐
     *  $pid            1：洗车券 2：满减券  3：折扣券
     *  $type_age       2；二年老用户  3:3年老用户  5:5年老用户
     **/
    public function gift_get_coupons( array $arr_input ){
        //洗车券没有商品使用类型
        if ($arr_input['pid'] == 1) {  //洗车券没有type属性
            $arr_option['where'] = ['pid' => $arr_input['pid'], 'status' => 1];
        } else {
            $arr_option['where'] = ['pid' => $arr_input['pid'], 'type' => $arr_input['type_shop'], 'status' => 1];
        }

        $arr_option['field'] = ['id','name'];
        //获取所有有关的优惠券列表
        $arr_list = CouponsRepository::get_all( (array) $arr_option)->toarray();


        if( $arr_input['type'] == 1 || $arr_input['type'] == 3 ){   //新用户礼包   或者  邀请礼包
            //获取当前类型是否已经设置过参数
            if( $arr_input['pid'] == 1 ){
                $arr_option2['where']= ['type_coupon'=>$arr_input['pid'] , 'type'=>$arr_input['type']];
            }else{      //洗车券
                $arr_option2['where']= ['type_coupon'=>$arr_input['pid'] , 'type_shop'=>$arr_input['type_shop'] , 'type'=>$arr_input['type']];
            }
        }else if( $arr_input['type'] == 2 || $arr_input['type'] == 4 || $arr_input['type'] == 5  ){       //老用户回馈礼包
            $arr_input['type'] = 2;
            if( $arr_input['pid'] == 1 ){
//                $arr_input['type_age'] = empty( $arr_input['type_age'] ) ? 2 : $arr_input['type_age'];
                $arr_option2['where']= ['type_coupon'=>$arr_input['pid'] , 'type'=>$arr_input['type'] , 'type_age'=>$arr_input['type_age']];
            }else{
                $arr_option2['where']= ['type_coupon'=>$arr_input['pid'] , 'type_shop'=>$arr_input['type_shop'] , 'type'=>$arr_input['type'] , 'type_age'=>$arr_input['type_age']];
            }
        }

        $arr_option2['field'] = ['id','coupon_id','number','validity_at'];
        $arr_list_gift = GiftExtendRepository::get_all( (array) $arr_option2)->toarray();
        foreach ( $arr_list as $key=>&$value){
            foreach ( $arr_list_gift as $k=>$vo){
                if( $value['id'] ==  $vo['coupon_id'] ){
                    $value['number'] = $vo['number'];
                    $value['validity_at'] = $vo['validity_at'];
                }
            }
        }
        return hello_success('ok',$arr_list);
    }

    /**
     *  获取指定类型的礼包数据详情
     *  hinq 2020 2 25
     *
     **/
    public function get_info( int $type , $age = '' ){
        try{
            if( !empty( $age ) ){
                $where['age'] = (int) $age;
            }
            if( in_array( $type , [4,5] ) ){   //老用户回馈
                $where['type'] = 2;
            }else{
                $where['type'] = $type;
            }

            $arr_option['field'] = ['id','type','title','age','number'];
            $arr_option['with'] = ['extend'];
            //获取指定数据的详细信息
            $arr_info = GiftRepository::get_one_by_where( (array) $where ,(array) $arr_option );
            if( !empty( $arr_info->first() ) ){
                $arr_info = $arr_info->toarray();
                $manjian_type_shop = '';    //满减券列表
                $manjian_coupons = [];      //满减券设置商品使用类型
                $zhekou_type_shop = '';     //折扣券列表
                $zhekou_coupons = [];       //折扣券设置的商品使用类型
                foreach ( $arr_info['extend'] as $key=>$vo ){
                    if( $vo['type_coupon'] == 2 ){  //满减券
                        $manjian_type_shop = $vo['type_shop'];
                        $arr_option1['where'] = ['pid'=>2,'type'=>$vo['type_shop']];
                    }
                    if( $vo['type_coupon'] == 3 ){   //折扣券
                        $zhekou_type_shop = $vo['type_shop'];
                        $arr_option2['where'] = ['pid'=>3,'type'=>$vo['type_shop']];
                    }
                }

                if( !empty( $arr_option1) ){
                    //获取对应的满减券下所有 type 对应类型的优惠券
                    $arr_option1['field'] = ['id','name'];
                    $manjian_coupons = CouponsRepository::get_all( (array) $arr_option1 )->toarray();
                    foreach ( $manjian_coupons as $key => &$vo ){
                        foreach ( $arr_info['extend'] as $k=>$v){
                            if( $vo['id'] == $v['coupon_id']){
                                $vo['number'] = $v['number'];
                                $vo['validity_at'] = $v['validity_at'];
                            }
                        }
                    }
                }

                if( !empty( $arr_option2) ){
                    //获取对应的折扣券下所有  type 对应类型的优惠券
                    $arr_option2['field'] = ['id','name'];
                    $zhekou_coupons = CouponsRepository::get_all( (array) $arr_option2 )->toarray();
                    foreach ( $zhekou_coupons as $key => &$vo ){
                        foreach ( $arr_info['extend'] as $k=>$v){
                            if( $vo['id'] == $v['coupon_id']){
                                $vo['number'] = $v['number'];
                                $vo['validity_at'] = $v['validity_at'];
                            }
                        }
                    }
                }
                $arr_info['manjian'] = [    //满减券数据
                    'type_shop' => $manjian_type_shop,
                    'coupons' => $manjian_coupons
                ];
                $arr_info['zhekou'] = [     //折扣券数据
                    'coupons' => $zhekou_coupons,       // 折扣券下所有满足条件的优惠券
                    'type_shop' => $zhekou_type_shop    // 折扣券设置的使用类型
                ];
                return hello_success('ok',$arr_info);
            }
            return hello_success('ok',[]);
        }catch (\Exception $exception){
            return hello_error($exception->getMessage());
        }
    }


    /**
     *  保存优惠券
     *  hinq 2020 2 25
     *
     **/
    public function store( array $arr_input){
        \DB::beginTransaction();      //开启事物
        try{
            $data['repairstore_id'] = 1;
            $data['status'] = 1;
            if( $arr_input['type'] == 2 || $arr_input['type'] == 4 || $arr_input['type'] == 5 ){
                $data['age'] = $arr_input['age'];
                $arr_input['type'] = 2;
            }elseif ( $arr_input['type'] == 3 ){
                $data['number'] = $arr_input['number'];
            }
            $data['type'] = $arr_input['type'];
            $res = GiftRepository::get_count_by_where( (array) $data );
            $data['title'] = $arr_input['title'];
            if( $res == 0 ){   //添加
                $res1 = GiftRepository::add_one( (array) $data );
                $res2 = true;
                if( isset( $arr_input['manjian'] ) ){
                    if(  !empty( array_filter( $arr_input['manjian'] ) ) ){ // 满减券
                        //添加其他的信息
                        $data2['gift_id'] = $res1->id;
                        $data2['type'] = $arr_input['type'];
                        if( $arr_input['type'] == 2 ){          //老顾客回馈是才有的参数
                            $data2['type_age'] = $arr_input['age'];
                        }
                        $data2['type_coupon'] = 2;
                        $data2['type_shop'] = $arr_input['type_coupon_manjian'];

                        foreach ( $arr_input['manjian'] as $key=>$vo ){
                            $data2['coupon_id'] = $vo;
                            $data2['number'] = $arr_input['manjian_number'][$key];
                            $data2['validity_at'] = $arr_input['manjian_validity_at'][$key];
                            $res2 = GiftExtendRepository::add_one( (array) $data2 );
                        }
                    }
                }
                $res3 = true;
                if( isset( $arr_input['zhekou'] ) ) {
                    if (!empty(array_filter($arr_input['zhekou']))) { // 折扣券
                        //添加其他的信息
                        $data3['gift_id'] = $res1->id;
                        $data3['type'] = $arr_input['type'];
                        if ($arr_input['type'] == 2) {              //老顾客回馈是才有的参数
                            $data3['type_age'] = $arr_input['age'];
                        }
                        $data3['type_coupon'] = 3;
                        $data3['type_shop'] = $arr_input['type_coupon_zhekou'];

                        foreach ($arr_input['zhekou'] as $key => $vo) {
                            $data3['coupon_id'] = $vo;
                            $data3['number'] = $arr_input['zhekou_number'][$key];
                            $data3['validity_at'] = $arr_input['zhekou_validity_at'][$key];
                            $res3 = GiftExtendRepository::add_one((array)$data3);
                        }
                    }
                }
                $res4 = true;
                if( isset( $arr_input['xiche'] ) || !empty( array_filter( $arr_input['xiche'] ) ) ){ // 洗车券
                    //添加其他的信息
                    $data4['gift_id'] = $res1->id;
                    $data4['type'] = $arr_input['type'];
                    if( $arr_input['type'] == 2 ){              //老顾客回馈是才有的参数
                        $data4['type_age'] = $arr_input['age'];
                    }
                    $data4['type_coupon'] = 1;
                    foreach ( $arr_input['xiche'] as $key=>$vo ){
                        $data4['coupon_id'] = $vo;
                        $data4['number'] = $arr_input['xiche_number'][$key];
                        $data4['validity_at'] = $arr_input['xiche_validity_at'][$key];
                        $res4 = GiftExtendRepository::add_one( (array) $data4 );
                    }
                }
                if( $res1 && $res2 && $res3 && $res4 ){
                    \DB::commit();
                    return hello_success('保存成功');
                }
            }else{
                //编辑礼包信息
                $data['title'] = $arr_input['title'];
                $data['id'] = $arr_input['id'];
                $res = GiftRepository::edit_one( (array) $data );

                //删除当前礼包之前设置的参数
                $where = ['gift_id' => $arr_input['id'] ];
                $res1 = GiftExtendRepository::delete_where( (array) $where );
                $res2 = true;
                if( isset( $arr_input['manjian'] ) ) {
                    if( !empty( $arr_input['manjian']) ){ // 满减券
                        //添加其他的信息
                        $data2['gift_id'] = $arr_input['id'];
                        $data2['type'] = $arr_input['type'];
                        if( $arr_input['type'] == 2 ){          //老顾客回馈是才有的参数
                            $data2['type_age'] = $arr_input['age'];
                        }
                        $data2['type_coupon'] = 2;
                        $data2['type_shop'] = $arr_input['type_coupon_manjian'];

                        foreach ( $arr_input['manjian'] as $key=>$vo ){
                            $data2['coupon_id'] = $vo;
                            $data2['number'] = $arr_input['manjian_number'][$key];
                            $data2['validity_at'] = $arr_input['manjian_validity_at'][$key];
                            $res2 = GiftExtendRepository::add_one( (array) $data2 );
                        }
                    }
                }

                $res3 = true;
                if( isset( $arr_input['zhekou'] ) ) {
                    if( !empty( $arr_input['zhekou']) ){ // 折扣券
                        //添加其他的信息
                        $data3['gift_id'] = $arr_input['id'];
                        $data3['type'] = $arr_input['type'];
                        if( $arr_input['type'] == 2 ){          //老顾客回馈是才有的参数
                            $data3['type_age'] = $arr_input['age'];
                        }
                        $data3['type_coupon'] = 3;
                        $data3['type_shop'] = $arr_input['type_coupon_zhekou'];

                        foreach ( $arr_input['zhekou'] as $key=>$vo ){
                            $data3['coupon_id'] = $vo;
                            $data3['number'] = $arr_input['zhekou_number'][$key];
                            $data3['validity_at'] = $arr_input['zhekou_validity_at'][$key];
                            $res3 = GiftExtendRepository::add_one( (array) $data3 );
                        }
                    }
                }
                $res4 = true;
                if( isset( $arr_input['xiche'] ) ) {
                    if( !empty( $arr_input['xiche']) ){ // 洗车券
                        //添加其他的信息
                        $data4['gift_id'] = $arr_input['id'];
                        $data4['type'] = $arr_input['type'];
                        if( $arr_input['type'] == 2 ){          //老顾客回馈是才有的参数
                            $data4['type_age'] = $arr_input['age'];
                        }
                        $data4['type_coupon'] = 1;

                        foreach ( $arr_input['xiche'] as $key=>$vo ){
                            $data4['coupon_id'] = $vo;
                            $data4['number'] = $arr_input['xiche_number'][$key];
                            $data4['validity_at'] = $arr_input['xiche_validity_at'][$key];
                            $res4 = GiftExtendRepository::add_one( (array) $data4 );
                        }
                    }
                }
                if( $res && $res1 && $res2 && $res3 && $res4 ){
                    \DB::commit();
                    return hello_success('更新成功');
                }
            }
        }catch (\Exception $exception){
            \DB::rollback();    //数据回滚
            return hello_error( $exception->getMessage());
        }
    }


    //新用户注册发放注册礼包
    public function gift_regiset( int $user_id ){
        return '已挪至公共的PublicService里面';
        /**
         *  1:每次新注册的用户都需要调用次函数
         *  2：验证新用户注册礼包是否开启
         *  3：获取新用户注册礼包设置的礼包数据信息（car_gifts和car_gift_extend）
         *  4：将新用户注册礼包发放到新用户账户中（car_coupon_grant_detail）
         *  5：记录发放日志
         **/
        // 获取保存的日志信息
//        dd( LogRepository::get_send_gift_log()->toarray());
        //验证注册礼包是否开启（由于现在控制功能为完善，暂且不验证）

        //获取平台设置的用户注册礼包数据
        $where['type'] = 1;
        $arr_option['field'] = ['id','type','title','age','number'];
        $arr_option['with'] = ['extend'];
        //获取指定数据的详细信息
        $arr_list = GiftRepository::get_one_by_where( (array) $where ,(array) $arr_option );
        if( empty( $arr_list->first() ) ){   // 没有设置新用户注册礼包
            return hello_success('ok');
        }
        $arr_list = $arr_list->toarray();

        //验证当前用户是都已经发放过用户注册礼包
        $where['type'] = 4;
        $where['user_id'] = $user_id;
        $count = CouponGrantDetailRepository::get_count_by_where( $where );
        if( $count > 0 ){  //当前用户已经发放过新用户注册礼包
            return hello_success('ok');
        }

        $temp['user_id'] = $user_id;
        $temp['msg'] = '新用户注册礼包';
        $temp['integral'] = 0;
        $temp['status'] = 1;
        $temp['type'] = 4;
        $xcq =0; $zkq = 0;  $mjq = 0;  $num = 0;
        //给用户发放新用户注册礼包
        foreach ( $arr_list['extend'] as $key=>$value ){
            for ( $i = 1 ; $i <=$value['number'] ; $i++ ) {
                if ($value['type_coupon'] == 1) {
                    $xcq++;
                } else if ($value['type_coupon'] == 2) {
                    $mjq++;
                } else if ($value['type_coupon'] == 3) {
                    $zkq++;
                }
                $num++;
                $temp['coupon_id'] = $value['coupon_id'];
                $temp['pid'] = $value['type_coupon'];
                $temp['over_at'] = time() + $value['validity_at'] * 60 * 60 * 24;
                $temp['ticket_num'] = set_coupons_ticket_num($value['type_coupon']);
                CouponGrantDetailRepository::add_one( $temp );
            }
        }
        $str = '已发放洗车券：'.$xcq.'张，满减券：'.$mjq.'张，折扣券：'.$zkq.'张,共计发放'.$num.'张';
        $arrlog = [
            'user_id' => $user_id,
            'send_time' => date('Y-m-d H:i:s'),
            'msg' => $str,
            'type' => 1,
            'type_msg' => '新用户注册礼包'
        ];
        //将发放新用户注册礼包的记录记录日志
        LogRepository::record_send_gift( (array) $arrlog );
    }


    /**
     *  用户邀请礼包发放
     *  $user_id       邀请者id
     *  $to_user_id    被邀请者id
     **/
    public function gift_invite( int $user_id , int $to_user_id){
        return '已挪至公共的PublicService里面';
        try{
            /**
             *  1：每次邀请新用户注册后调用次函数
             *  2：验证邀请礼包是否开启
             *  3：验证邀请用户和被邀请用户数据的有效性
             *  4：添加邀请信息
             *  5：计算当前次数邀请是否满足邀请礼包的发放
             *  6：发放邀请礼包
             *  7：记录邀请礼包发放日志
             **/
            //验证邀请礼包是否开启（由于现在控制功能为完善，暂且不验证）

            //验证数据的有效性
            //是否重复提交数据
            $where = ['user_id'=>$user_id , 'to_user_id'=>$to_user_id];
            $count = UserInviteRepository::get_count_by_where( (array) $where );
            if( $count > 0 ){
                return hello_error('请勿重复提交');
            }
            unset( $where );
            //被邀请者是否只被邀请过一次
            $where = ['to_user_id'=>$to_user_id];
            $count = UserInviteRepository::get_count_by_where( (array) $where );
            if( $count > 0 ){
                return hello_error('被邀请者被重复邀请');
            }
            $data['user_id'] = $user_id;
            $data['to_user_id'] = $to_user_id;
            $data['type'] = 0;
            $res = UserInviteRepository::add_one( (array) $data );

            \DB::beginTransaction();      //开启事物
            //统计邀请者已邀请且未别计算的人数
            unset( $where );
            $where = ['user_id'=>$user_id , 'type'=>0];
            $count = UserInviteRepository::get_count_by_where( (array) $where );

            //获取平台设置的邀请者礼包
            //获取平台设置的用户注册礼包数据
            unset( $where );
            $where['type'] = 3;
            $arr_option['field'] = ['id','number'];
            $arr_option['with'] = ['extend'];
            //获取指定数据的详细信息
            $arr_list = GiftRepository::get_one_by_where( (array) $where ,(array) $arr_option );
            if( empty( $arr_list->first() ) ){
                return hello_error('未设置邀请礼包');
            }
            $arr_list = $arr_list->toarray();
            //邀请人数  >= 平台设置邀请人数
            if( $count < $arr_list['number'] ){   //给邀请者发放邀请礼包
                return hello_success('邀请人数不满足邀请礼包的发放');
            }
            $xcq = 0 ; $zkq = 0 ; $mjq = 0; $num = 0;
            $temp['user_id'] = $user_id;
            $temp['msg'] = '分享邀请获取礼包';
            $temp['integral'] = 0;
            $temp['status'] = 1;
            $temp['type'] = 2;
            $res2 = true;
            foreach ( $arr_list['extend'] as $key=>$vo){
                for ( $i =1 ; $i<= $vo['number'] ; $i++ ) {
                    if ($vo['type_coupon'] == 1) {
                        $xcq++;
                    } else if ($vo['type_coupon'] == 2) {
                        $mjq++;
                    } else if ($vo['type_coupon'] == 3) {
                        $zkq++;
                    }
                    $num++;
                    $temp['coupon_id'] = $vo['coupon_id'];
                    $temp['pid'] = $vo['type_coupon'];
                    $temp['over_at'] = time() + $vo['validity_at'] * 60 * 60 * 24;
                    $temp['ticket_num'] = set_coupons_ticket_num($vo['type_coupon']);
                    $res2 = CouponGrantDetailRepository::add_one( $temp );
                }
            }
            $str = '已发放洗车券：'.$xcq.'张，满减券：'.$mjq.'张，折扣券：'.$zkq.'张,共计发放'.$num.'张';
            $arrlog = [
                'user_id' => $user_id,
                'send_time' => date('Y-m-d H:i:s'),
                'msg' => $str,
                'type' => 1,
                'type_msg' => '新用户注册礼包'
            ];
            //将发放新用户注册礼包的记录记录日志
            $res3 = LogRepository::record_send_gift( (array) $arrlog );

            #将人员设置为已发放
            ##获取当前满足人员的数量
            $arr_option2['where'] = ['user_id'=>$user_id , 'type'=>0];
            $arr_option2['n_per_page'] = $arr_list['number'];
            $arr_option2['first'] = ['id'];
            $arr_option2['order'] =['key'=>'id' , 'value'=>'asc'];
            $arr_list = UserInviteRepository::get_all_to_limit( (array) $arr_option2 )->toarray();
            $last_id = '';

            foreach ($arr_list as $key=>$vo){
                $last_id = $vo['id'];
            }
            ##修改数据表状态
            $data2['type'] = 1;
            $where2 = ['user_id'=>$user_id];
            $res4 = UserInviteRepository::edit_by_where( (array) $where2 , (array) $data2 , (int) $last_id);
            if( $res2 && $res3 && $res4 ){
                \DB::commit();
                return hello_success('邀请礼包发放成功');
            }
        }catch (\Exception $exception){
            \DB::rollback();    //数据回滚
            return hello_error($exception->getMessage());
        }
    }


    //老用户回馈礼包
    public function gift_old(){
        return '已挪至公共的PublicService里面';
        dd(LogRepository::get_send_gift_log()->toarray());

        \DB::beginTransaction();      //开启事物
        try{
            /**
             *  1：新年的第一天自动执行次函数
             *  2：验证当前礼包是否开启
             *  3：获取礼包的数据详情
             *  4：获取满足条件的所有用户信息
             *  5：将礼包发放给各个满足条件的用户
             *  6：记录礼包发放日志
             **/
            //验证邀请礼包是否开启（由于现在控制功能为完善，暂且不验证）

            $arr_option['field'] = ['id','age'];
            $arr_option['with'] = ['extend'];
            $arr_option['where'] = ['type'=>2];
            //获取指定数据的详细信息
            $arr_list = GiftRepository::get_all( (array) $arr_option )->toarray();
            $age2 = [] ; $age3 = [] ; $age5 = [];
            //#分别取出不同年限的礼包
            foreach ( $arr_list as $key => $vo ){
                if( $vo['age'] == 2 ){  //2年
                    $age2 = $vo['extend'];
                }
                if( $vo['age'] == 3 ){  //3年
                    $age3 = $vo['extend'];
                }
                if( $vo['age'] == 5 ){  //5年
                    $age5 = $vo['extend'];
                }
            }

            //获取用户的列表信息
            $time1 = date("Y-01-01 00:00:00", strtotime("-2 year")); //获取格式为2016-12-30 13:26:13
            $time2 = date("Y-01-01 00:00:00", strtotime("-3 year")); //获取格式为2016-12-30 13:26:13
            $time3 = date("Y-01-01 00:00:00", strtotime("-5 year")); //获取格式为2016-12-30 13:26:13
            $res2 =true; $res3 =true; $res5 =true;
            $xcq = 0 ; $zkq = 0 ; $mjq = 0; $num = 0; $ids = '';
            if( count( $age2 ) > 0 ){  //设置了2年礼包
                //# 获取满足2年并且小于3年的老用户
                $arr_list2 = UsersRepository::get_where_list( (array)[ 'time1' => $time1 , 'time2' => $time2 ] )->toarray();
                if( count( $arr_list2  ) > 0 ){
                    foreach ( $arr_list2 as $key => $value ){
                        $ids .= $value['id'] . ',';
                        $temp2['user_id'] = $value['id'];
                        $temp2['msg'] = '2年老用户回馈礼包';
                        $temp2['integral'] = $value['integral_all'];
                        $temp2['status'] = 1;
                        $temp2['type'] = 5;
                        foreach ( $age2 as $k => $vo ){
                            for ( $i = 1 ; $i <= $vo['number'] ; $i++ ){
                                if ($vo['type_coupon'] == 1) {
                                    $xcq++;
                                } else if ($vo['type_coupon'] == 2) {
                                    $mjq++;
                                } else if ($vo['type_coupon'] == 3) {
                                    $zkq++;
                                }
                                $num++;
                                $temp2['coupon_id'] = $vo['coupon_id'];
                                $temp2['pid'] = $vo['type_coupon'];
                                $temp2['over_at'] = time() + $vo['validity_at'] * 60 * 60 * 24;
                                $temp2['ticket_num'] = set_coupons_ticket_num($vo['type_coupon']);
                               $res2 = CouponGrantDetailRepository::add_one( $temp2 );
                            }
                        }
                    }
                    $str2 = '已发放洗车券：'.$xcq.'张，满减券：'.$mjq.'张，折扣券：'.$zkq.'张,共计发放'.$num.'张';
                    $arrlog = [
                        'user_id' => trim(  $ids ,',' ),
                        'send_time' => date('Y-m-d H:i:s'),
                        'msg' => $str2,
                        'type' => 2,
                        'type_msg' => '2年老用户回馈礼包'
                    ];
                    //将发放新用户注册礼包的记录记录日志
                    LogRepository::record_send_gift( (array) $arrlog );
                }
            }
            $xcq = 0 ; $zkq = 0 ; $mjq = 0; $num = 0; $ids = '';
            if( count( $age3 ) > 0 ){  //设置了2年礼包
                //#获取满足3年并且小于5年的老用户
                $arr_list3 = UsersRepository::get_where_list( (array)[ 'time1' => $time2 , 'time2' => $time3 ] )->toarray();
                if( count( $arr_list3  ) > 0 ){
                    foreach ( $arr_list3 as $key => $value ){
                        $ids .= $value['id'] . ',';
                        $temp3['user_id'] = $value['id'];
                        $temp3['msg'] = '3年老用户回馈礼包';
                        $temp3['integral'] = $value['integral_all'];
                        $temp3['status'] = 1;
                        $temp3['type'] = 5;
                        foreach ( $age3 as $k => $vo ){
                            for ( $i = 1 ; $i <= $vo['number'] ; $i++ ){
                                if ($vo['type_coupon'] == 1) {
                                    $xcq++;
                                } else if ($vo['type_coupon'] == 2) {
                                    $mjq++;
                                } else if ($vo['type_coupon'] == 3) {
                                    $zkq++;
                                }
                                $num++;
                                $temp3['coupon_id'] = $vo['coupon_id'];
                                $temp3['pid'] = $vo['type_coupon'];
                                $temp3['over_at'] = time() + $vo['validity_at'] * 60 * 60 * 24;
                                $temp3['ticket_num'] = set_coupons_ticket_num($vo['type_coupon']);
                                $res3 = CouponGrantDetailRepository::add_one( $temp3 );
                            }
                        }
                    }
                    $str3 = '已发放洗车券：'.$xcq.'张，满减券：'.$mjq.'张，折扣券：'.$zkq.'张,共计发放'.$num.'张';
                    $arrlog = [
                        'user_id' => trim(  $ids ,',' ),
                        'send_time' => date('Y-m-d H:i:s'),
                        'msg' => $str3,
                        'type' => 2,
                        'type_msg' => '3年老用户回馈礼包'
                    ];
                    //将发放新用户注册礼包的记录记录日志
                    LogRepository::record_send_gift( (array) $arrlog );
                }
            }

            $xcq = 0 ; $zkq = 0 ; $mjq = 0; $num = 0; $ids = '';
            if( count( $age5 ) > 0 ){  //设置了2年礼包
                //#获取满足5年的老用户
                $arr_list5 = UsersRepository::get_where_list( (array)[ 'time1' => $time3 ]   )->toarray();
                if( count( $arr_list5  ) > 0 ){
                    foreach ( $arr_list5 as $key => $value ){
                        $ids .= $value['id'] . ',';
                        $temp5['user_id'] = $value['id'];
                        $temp5['msg'] = '5年老用户回馈礼包';
                        $temp5['integral'] = $value['integral_all'];
                        $temp5['status'] = 1;
                        $temp5['type'] = 5;
                        foreach ( $age5 as $k => $vo ){
                            for ( $i = 1 ; $i <= $vo['number'] ; $i++ ){
                                if ($vo['type_coupon'] == 1) {
                                    $xcq++;
                                } else if ($vo['type_coupon'] == 2) {
                                    $mjq++;
                                } else if ($vo['type_coupon'] == 3) {
                                    $zkq++;
                                }
                                $num++;
                                $temp5['coupon_id'] = $vo['coupon_id'];
                                $temp5['pid'] = $vo['type_coupon'];
                                $temp5['over_at'] = time() + $vo['validity_at'] * 60 * 60 * 24;
                                $temp5['ticket_num'] = set_coupons_ticket_num($vo['type_coupon']);
                                $res5 = CouponGrantDetailRepository::add_one( $temp5 );
                            }
                        }
                    }
                    $str5 = '已发放洗车券：'.$xcq.'张，满减券：'.$mjq.'张，折扣券：'.$zkq.'张,共计发放'.$num.'张';
                    $arrlog = [
                        'user_id' => trim(  $ids ,',' ),
                        'send_time' => date('Y-m-d H:i:s'),
                        'msg' => $str5,
                        'type' => 2,
                        'type_msg' => '5年老用户回馈礼包'
                    ];
                    //将发放新用户注册礼包的记录记录日志
                    LogRepository::record_send_gift( (array) $arrlog );
                }
            }

            if( $res2 && $res3 && $res5 ){
                \DB::commit();
                return hello_success('老用户回馈礼包发放成功');
            }
        }catch (\Exception $exception){
            \DB::rollback();    //数据回滚
            return hello_error($exception->getMessage());
        }
    }


}